package cn.net.dckj.web.controller.system;

import cn.net.dckj.common.annotation.Log;
import cn.net.dckj.common.core.controller.BaseController;
import cn.net.dckj.common.core.domain.AjaxResult;
import cn.net.dckj.common.core.page.TableDataInfo;
import cn.net.dckj.common.enums.BusinessType;
import cn.net.dckj.common.utils.StringUtils;
import cn.net.dckj.common.utils.file.FileUploadUtils;
import cn.net.dckj.common.utils.file.FileUtils;
import cn.net.dckj.common.utils.file.ftp.FTPProperties;
import cn.net.dckj.common.utils.file.ftp.FTPUtils;
import cn.net.dckj.system.domain.SysAttachment;
import cn.net.dckj.system.service.ISysAttachmentService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 系统附件Controller
 *
 * @author dckj
 * @date 2019-10-15
 */
@Controller
@RequestMapping("/system/attachment")
public class SysAttachmentController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(SysAttachmentController.class);
    private String prefix = "system/attachment";

    @Autowired
    private ISysAttachmentService sysAttachmentService;

    @Autowired
    private FTPProperties ftpProperties;

    @RequiresPermissions("system:attachment:view")
    @GetMapping()
    public String attachment(Long mainId, String entityName, String isView, String viewMode, ModelMap mmap) {
        if (mainId == null) mainId = -1L;
        if (StringUtils.isEmpty(entityName)) entityName = "";
        // isView-是否查看，1查看，非1(0)编辑
        if (StringUtils.isEmpty(isView)) isView = "0";
        mmap.put("mainId" , mainId);
        mmap.put("entityName" , entityName);
        mmap.put("isView" , isView);
        if ("list".equals(viewMode)) {
            return prefix + "/attachmentList";
        } else if ("tile".equals(viewMode)) {
            return prefix + "/attachmentTile";
        } else {
            return prefix + "/attachmentList";
        }
    }

    /**
     * 查询系统附件列表
     */
    @RequiresPermissions("system:attachment:view")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(SysAttachment sysAttachment) {
        List<SysAttachment> list = new ArrayList<SysAttachment>();
        if ("tile".equals(sysAttachment.getViewMode())) {
            list = sysAttachmentService.selectSysAttachmentList(sysAttachment);
        } else {
            startPage();
            list = sysAttachmentService.selectSysAttachmentList(sysAttachment);
        }
        return getDataTable(list);
    }

    /**
     * 新增系统附件
     */
    @GetMapping("/add")
    public String add(Long mainId, String entityName, ModelMap mmap) {
        if (mainId == null) mainId = -1L;
        if (StringUtils.isEmpty(entityName)) entityName = "";
        mmap.put("mainId" , mainId);
        mmap.put("entityName" , entityName);
        return prefix + "/add";
    }

    /**
     * 新增保存系统附件
     */
    @RequiresPermissions("system:attachment:edit")
    @Log(title = "系统附件" , businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(MultipartFile file, SysAttachment sysAttachment) {
        try {
            if (file.isEmpty()) {
                return error("附件上传失败！原因：文件不存在！");
            }
            String fileName = file.getOriginalFilename();
            long fileSize = file.getSize();
            String fileType = FileUploadUtils.getExtension(file);
            String uploadPath = ftpProperties.getUploadUrl();
            String filePath = FTPUtils.getInstance().uploadFile(uploadPath, file);
            sysAttachment.setAttachmentName(fileName);
            sysAttachment.setAttachmentSize(fileSize);
            sysAttachment.setAttachmentType(fileType);
            sysAttachment.setAttachmentPath(filePath);
            return toAjax(sysAttachmentService.insertSysAttachment(sysAttachment));
        } catch (Exception e) {
            return error("附件上传失败！原因：" + e.getMessage());
        }
    }

    /**
     * 修改系统附件
     */
    /*@GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap) {
        SysAttachment sysAttachment = sysAttachmentService.selectSysAttachmentById(id);
        mmap.put("sysAttachment" , sysAttachment);
        return prefix + "/edit";
    }*/

    /**
     * 修改保存系统附件
     */
    /*@RequiresPermissions("system:attachment:edit")
    @Log(title = "系统附件" , businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(SysAttachment sysAttachment) {
        return toAjax(sysAttachmentService.updateSysAttachment(sysAttachment));
    }*/

    /**
     * 删除系统附件
     */
    @RequiresPermissions("system:attachment:edit")
    @Log(title = "系统附件" , businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(sysAttachmentService.deleteSysAttachmentByIds(ids));
    }

    /**
     * 查看系统附件详细信息
     */
    @RequiresPermissions("system:attachment:view")
    @GetMapping("/detail/{id}")
    public String detail(@PathVariable("id") Long id, ModelMap mmap) {
        SysAttachment sysAttachment = sysAttachmentService.selectSysAttachmentById(id);
        mmap.put("sysAttachment" , sysAttachment);
        return prefix + "/detail";
    }

    /**
     * 下载系统附件
     *
     * @param response
     */
    @RequiresPermissions("system:attachment:view")
    @GetMapping("/download/{id}")
    public void download(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) {
        try {
            SysAttachment sysAttachment = sysAttachmentService.selectSysAttachmentById(id);
            String attachmentName = sysAttachment.getAttachmentName();
            String attachmentPath = sysAttachment.getAttachmentPath();

            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition" ,
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, attachmentName));
            FTPUtils.getInstance().downFile(attachmentPath, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败" , e);
        }
    }
}
